//
//  SCPhotoBrowserCell.swift
//  GZWeibo007
//
//  Created by newuser on 15/12/31.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

import SDWebImage

import SVProgressHUD

import FLAnimatedImage

let ImageViewMinimumZoomScale: CGFloat = 0.5

// 当缩放完毕小于此缩放比例时,自动关闭控制器
let dismissZoomScale: CGFloat = 0.75

class SCPhotoBrowserCell: UICollectionViewCell {
   
    //MARK: - 属性
    ///cell缩放代理
    var cellDelegate: SCPhotoBrowserCellDelegate?
    
    var imageURL: NSURL? {
        didSet {
            //清空
            imageView.image = nil
            //清空属性
            resetPriterties()
            ///显示
//            indicator.startAnimating()
//            
//            imageView.sd_setImageWithURL(imageURL) { (image, error, _, _) -> Void in
//                
//                self.indicator.stopAnimating()
//                if error != nil {
//                    print("下载失败")
//                    return
//                }
////                self.imageView.sizeToFit()
//                self.layoutImageView(image)
//            }
//       
            //判断是否已经下载
            // SDWebIamage默认保存图片的路径
            //判断是否已经下载
            // SDWebIamage默认保存图片的路径
            let path = SDWebImageManager.sharedManager().imageCache.defaultCachePathForKey(imageURL?.absoluteString)
            //加载数据
            let data = NSData(contentsOfFile: path)
            if data != nil {
                //表示之前有缓存
                let image = UIImage(data: data!)!
                self.setImage(image, data: data!)
                return
            }
            //下载并显示
            SDWebImageDownloader.sharedDownloader().downloadImageWithURL(imageURL, options: SDWebImageDownloaderOptions(rawValue: 0), progress: { (receive, total) -> Void in
                let progress = Float(receive) / Float(total)
                //在主线程更新ui
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    //有进度的提示
                    SVProgressHUD.showProgress(progress)
                })
                }) { (image, data, error, finished) -> Void in
                    print("下载图片完成")
                    SDWebImageManager.sharedManager().imageCache.storeImage(image, recalculateFromImage: false, imageData: data, forKey: self.imageURL?.absoluteString, toDisk: true)
                    //显示照片
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.setImage(image, data: data)
                    })
            }
        }
    }
    
    ///设置照片
    private func setImage(image: UIImage, data: NSData) {
        // 判断图片类型,是否是gif图片
        let gif = self.imageURL!.absoluteString.lowercaseString.hasSuffix("gif")
        
        // 如果不是gif图片
        if !gif {
            // 显示普通图片
            self.imageView.image = image
        } else {
            // 创建gifImage
            let animatedImage = FLAnimatedImage(animatedGIFData: data)
            // 显示gif图片 FLAnimatedImage
            self.imageView.animatedImage = animatedImage
        }
        
        SVProgressHUD.dismiss()
        // 修改imageView的大小
        self.layoutImageView(image)
    }
    
    //清空scrollview的属性
    private func resetPriterties() {
    
         imageView.transform = CGAffineTransformIdentity
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentSize = CGSizeZero
        scrollView.contentOffset = CGPointZero
    
    }

    
    ///重新布局imageview的frame
    private func layoutImageView(image: UIImage) {
       //计算缩放
        let newSize = displaySize(image)
        
        //判断长短图
        if newSize.height < UIScreen.mainScreen().bounds.height {
        
            //设置照片frame
            imageView.frame = CGRectMake(0, 0, newSize.width, newSize.height)
            //短图,居中
            let offestY = (UIScreen.mainScreen().bounds.height - newSize.height)  * 0.5
  
            scrollView.contentInset = UIEdgeInsetsMake(offestY, 0, offestY, 0)
            
        }else {
            //长途
            imageView.frame = CGRect(origin: CGPointZero, size: newSize)
            
            //设置滚动范围
            scrollView.contentSize = newSize
            
        }
        
    
    }
    ///将图片灯比例的缩放等于屏幕
    private func displaySize(image: UIImage) -> CGSize {
        let newWidth = UIScreen.mainScreen().bounds.width
        let newHeight = newWidth * image.size.height / image.size.width
        //返回
        return CGSize(width: newWidth, height: newHeight)
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
//MARK: - 准备UI
    func prepareUI() {
        
        scrollView.delegate = self
        //设置缩放比例
        scrollView.maximumZoomScale = 2
        scrollView.minimumZoomScale = ImageViewMinimumZoomScale
        scrollView.backgroundColor = UIColor.clearColor()
        //添加子控件
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        contentView.addSubview(indicator)
        //添加约束
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        indicator.translatesAutoresizingMaskIntoConstraints = false
        
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv" : scrollView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv" : scrollView]))
    
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        
    }
    
    
    
    //MARK: - 懒加载控件
    private lazy var scrollView = UIScrollView()
    //照片
    lazy var imageView: SCImageView = SCImageView()
   
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
}

//cell缩放的代理
protocol SCPhotoBrowserCellDelegate: NSObjectProtocol {
   //获取代理控制器的背景
    func viewForTransparent() -> UIView
    
    //通知控制器关闭
    func cellForDismissController()
    
    //获取缩略图的位置
    func targetRectForDismissController() -> CGRect
    
}





//MARK; - 扩展--> scrollview的代理
extension SCPhotoBrowserCell:UIScrollViewDelegate {

    ///返回要缩放的照VIEW
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    ///scrollView每次缩放都会调用
    func scrollViewDidZoom(scrollView: UIScrollView) {
        //修改控制器的背景透明度
        let bkgVie = cellDelegate?.viewForTransparent()
        
        //计算alpha
        let alpha = imageView.transform.a * 0.7 + 0.2
        
        //设置alpha
        if alpha < 1 {
        
            bkgVie?.alpha = alpha
        }else {
        
            bkgVie?.alpha = 1
        }
    }
    
    
    
    
//    缩放后的大小,使用frame
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat)  {
        
        if scale < dismissZoomScale {
           //线动画到所里位置
            if let newFrame = cellDelegate?.targetRectForDismissController() {
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.imageView.clipsToBounds = true
                    self.imageView.frame = CGRect(origin: CGPointZero, size: newFrame.size)
                    //顶部和左边需要间距
                    scrollView.contentInset = UIEdgeInsets(top: newFrame.origin.y, left: newFrame.origin.x, bottom: 0, right: 0)
                    scrollView.contentOffset.x = -newFrame.origin.x
                    scrollView.contentOffset.y = -newFrame.origin.y
                    }, completion: { (_) -> Void in
                        self.cellDelegate?.cellForDismissController()
                })
            
            }
            
        } else {
        
        // 居中图片
        var offestX = (scrollView.bounds.width - imageView.frame.width) * 0.5
        var offestY = (scrollView.bounds.height - imageView.frame.height) * 0.5
        
        // 判断 offestX,offestY 不能小于0, offestX > 0 会往右边顶, offestX < 0会往左边扯,有一些内容会看不到,当offestX < 0 时 offestX = 0
        offestX = offestX < 0 ? 0 : offestX
        offestY = offestY < 0 ? 0 : offestY
        
        UIView.animateWithDuration(0.25) { () -> Void in
            scrollView.contentInset = UIEdgeInsets(top: offestY, left: offestX, bottom: offestY, right: offestX)
       }
    }
  }
}